package cn.enjoy.rocketmq.producer;

import lombok.AllArgsConstructor;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author K
 * @date 2021/6/3 下午3:35
 */
@RestController
@AllArgsConstructor
public class Producer {

    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送普通消息
     */
    @PostMapping("sendMessageCommon")
    public void sendMessageCommon(String msg, Boolean defaultTag, @RequestParam() Integer count) {
        String topic = "boot";
        String tag = "TagTest";
        if (!defaultTag) {
            tag = "TagTest2";
        }
        String destination = topic + ":" + tag;
        for (int i = 0; i < count; i++) {
            SendResult sendResult = rocketMQTemplate.syncSend(destination, msg);
            // 或者
//        rocketMQTemplate.convertAndSend(destination, msg);
        }
    }

    /**
     * 发送事务消息
     */
    @PostMapping("sendMessageInTransaction")
    public void sendMessageInTransaction(String msg) {
        String topic = "transaction";
        String[] tags = new String[]{"TagA", "TagB", "TagC", "TagD", "TagE"};
        for (int i = 0; i < 10; i++) {
            Message<String> message = MessageBuilder.withPayload(msg + tags[i % tags.length]).build();
            String destination = topic + ":" + tags[i % tags.length];
            TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(destination, message, destination);
            System.out.printf("%s%n", transactionSendResult);
        }
    }

}
